#认证-验权中间件
from django.utils.deprecation import MiddlewareMixin
from django.http import JsonResponse
from app01.woutils.user_jwt import ParseToekn
from django.http import HttpResponse, Http404

class login(MiddlewareMixin):
    '''验证是否登录'''
    def process_request(self,request):
        try:
            url=request.path_info.split('/')
            if url[2] == 'login':  #允许访问登录接口
                return
            if len(url) > 3:
                if url[3] == "excel":
                    return
            #验证是否登录 或者登录是否有效
            token = request.META.get('HTTP_AUTHORIZATION')  # 获取token
            token_dic,err =  ParseToekn(token)
            if err != None:
                data={
                    "code":401,
                    "msg":"未登录或登录已过期",
                    "data":""
                }
                return JsonResponse(data)
        except Exception as e:
            # print("未提供资源",request.path_info,e)
            data = {
                "code": 503,
                "msg": "未提供资源",
                "data": ""
            }
            # return JsonResponse(data)
            raise Http404("No MyModel matches the given query.")

        return


    def process_response(self,request,response):
        return response



class admin(MiddlewareMixin):
    '''验证管理身份'''
    def process_request(self,request):
        url=request.path_info.split('/')
        if len(url) < 3:
            return
        if url[2] == 'login':
            return
        #验证是否为管理员可以访问的接口
        if url[2] != 'admin':
            return

        #解密token
        token = request.META.get('HTTP_AUTHORIZATION')  # 获取token
        token_dic,err =  ParseToekn(token)
        if err != None:
            data={
                "code":401,
                "msg":"未登录或登录已过期",
                "data":""
            }
            return JsonResponse(data)

        #验证等级是否为管理员
        if token_dic['data']['level'] != 10 :
            data = {
                "code": 403,
                "msg": "限权不足",
                "data": ""
            }
            return JsonResponse(data)
        return


    def process_response(self,request,response):
        return response
